<template>
    <div>
        <el-card shadow="never">
            <el-alert title="添加商品信息" type="info" show-icon:closable="false"></el-alert>
            <el-steps :active="Number(activeStep)" align-center finish-status="success">
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>

            <el-tabs tab-position="left" v-model="activeStep" :before-leave="beforeLeave" @tab-change="tabChange">
                <el-tab-pane name="0" label="基本信息">
                    <el-form :model="goodsForm" :rules="goodsFormRules" label-position="top" ref="goodsFormRef">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="goodsForm.goods_name"> </el-input>
                        </el-form-item>

                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader v-model="goodsForm.goods_cat" :options="options" :props="props"
                                @change="handleChange" :clearable="true" placeholder="请选择"></el-cascader>
                        </el-form-item>

                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="goodsForm.goods_price" type="number"> </el-input>
                        </el-form-item>

                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="goodsForm.goods_number" type="number"> </el-input>
                        </el-form-item>

                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="goodsForm.goods_weight" type="number"> </el-input>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane name="1" label="商品参数">
                    <div v-for="item, index in manyParams" :key="index" v-show="item.attr_vals.length">
                        <h5>{{ item.attr_name }}</h5>
                        <el-checkbox-group v-model="manyCheckList[index]" @change="changeCheckboc">
                            <el-checkbox :label="item1" size="large" border v-for="item1, index1 in item.attr_vals"
                                :key="index1">
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-tab-pane>
                <el-tab-pane name="2" label="商品属性">
                    <div v-for="item, index in onlyParmas" :key="index" v-show="item.attr_vals.length">
                        <h5>{{ item.attr_name }}</h5>
                        <el-radio-group v-model="onlyRadioList[index]">
                            <el-radio :label="item1" size="large" border v-for="item1, index1 in item.attr_vals">
                                {{ item1 }}
                            </el-radio>
                        </el-radio-group>
                    </div>
                </el-tab-pane>
                <el-tab-pane name="3" label="商品图片">
                    <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" :on-preview="handlePreview"
                        :on-remove="handleRemove" :file-list="fileList" list-type="picture-card" class="upload-demo"
                        :headers="uploadHeaders" :on-success="onSuccess">
                        <el-button type="primary">上传商品图片</el-button>
                        <template #tip>
                            <div class="el-upload_tip">
                                图片要求：jpg/png文件格式，500kb以内。
                            </div>
                        </template>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane name="4" label="商品内容">
                    <editor api-key="zb75rg0hxvcgq85ox6rkhe4f4l0t2h27tk44ou0kn3dd1a5y" :init="editorInit"
                        v-model="goods_inroduce" />
                    <el-button style="margin:20px auto" type="primary" class="add-goods-btn"
                        @click="addGoods">添加商品</el-button>
                </el-tab-pane>

            </el-tabs>
        </el-card>
        <el-dialog>
            <el-image :src="dialogImageUrl" alt="dialogImageAlt"></el-image>
        </el-dialog>
    </div>
</template>
<script setup>
import axios from 'axios';
import { ElMessage } from 'element-plus'
import { ref, reactive, onBeforeMount } from 'vue'
import Editor from '@tinymce/tinymce-vue'
import { useRouter } from 'vue-router'
/* 富文本编辑器配置 */
const editorInit = {
    selector: '#tinymce',//容器，可使用css选择器
    language: 'zh-Hans',
    language_url: '/static/tinymce/langs/zh-Hans.js ',//在public下面
    deprecation_warnings: false,//去掉没用的warning
    height: 300,
    branding: false,//去掉底部水印
    statusbar: false,// 隐藏底部状态栏
    elementpath: false,// 禁用底部状态栏
    menubar: false,//隐藏最上方menu
    plugins: 'table contextmenu image',// 引人插件
    toolbar: 'bold italic underline strikethrough image table / fontsizeselect | alignleft aligncenter alignright alignjustify loutdent indent blockquote / undo redo / removeformat' //菜单配置（一个单词代表了一个功能)
}


let activeStep = ref('0')
const goodsForm = reactive({
    goods_name: '',
    goods_cat: [],
    goods_price: 0,
    goods_number: 0,
    goods_weight: 0
})
const goodsFormRules = reactive({
    goods_name: [
        {
            required: true, message: '请输入商品名称', trigger: 'blur'
        }
    ], goods_cat: [
        {
            required: true, message: '请输入商品分级，必须选到三级分类', trigger: 'change'
        }
    ], goods_price: [
        {
            required: true, message: '请输入商品价格', trigger: 'blur'
        }
    ], goods_number: [
        {
            required: true, message: '请输入商品数量', trigger: 'blur'
        }
    ], goods_weight: [
        {
            required: true, message: '请输入商品重量', trigger: 'blur'
        }
    ]
})

const options = ref([])
const props = {
    expandTrigger: 'hover',
    value: 'cat_id',
    label: 'cat_name'
}
const getCateList = async () => {
    const { data: res } = await axios.get(`categories`)
    if (res.meta.status !== 200) return
    options.value = res.data
}

onBeforeMount(() => {
    getCateList()
})

const handleChange = (value) => {
    if (value == null || goodsForm.goods_cat.length !== 3)
        return goodsForm.goods_cat = []
}

const goodsFormRef = ref(null)
const beforeLeave = (activeName, oldActiveName) => {
    if (oldActiveName === '0') goodsFormRef.value.validate((valid) => {
        if (!valid) {
            activeStep.value = '0'
        }
    })
}
const manyParams = ref([])
const manyCheckList = ref([])
const onlyParmas = ref([])
const onlyRadioList = ref([])
const getParams = async (sel) => {
    const { data: res } = await axios.get(`categories/${goodsForm.goods_cat[2]}/attributes?sel=${sel}`)
    console.log(res);
    if (res.meta.status !== 200) return
    // if(sel==='many')
    // {
    //     manyParams.value=res.data
    //     manyParams.value.forEach((val,index)=>{
    //         val.attr._vals=val.attr_vals.split(',')
    //         manyCheckList.value[index]=[]
    //     })
    // }
    res.data.forEach(val => val.attr_vals = val.attr_vals ? val.attr_vals.split(',') : '')
    if (sel === 'many') return manyParams.value = res.data
    if (sel === 'only') return onlyParmas.value = res.data
}
const tabChange = (name) => {
    if (name === '1') return getParams('many')
    if (name == '2') return getParams('only')
}

const changeCheckboc = () => {
    console.log(manyCheckList.value);
}

const fileList = ref([
])
const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
}
const handlePreview = (file) => {
    dialogImageUrl.value = file.url
    dialogImageVisible.value = true
    dialogImageAlt.value = file.name
    console.log(file);
}

const uploadHeaders = {
    Authorization: window.localStorage.getItem('token')
}

const onSuccess = (val) => {
    val.name = val.data.url
    var arr = val.name.split("\\");
    val.name = arr[arr.length - 1]; 
    fileList.value.push(val)
    console.log(val);
}

const dialogImageVisible = ref(false)
const dialogImageUrl = ref('')
const dialogImageAlt = ref('')
const goods_inroduce = ref('')
const router = useRouter()
const addGoods = async () => {
    // 添加商品
    console.log("添加商品");
    //生成图片数组pics
    let pics = []
    let key = ''
    if (fileList.value.length > 0) {
        fileList.value.forEach((val, index) => {
            // 初始化pics存放对象
            pics[index] = {}
            // 对象的key
            key = val.name
            // key对应的value
            pics[index][key] = val.data.tmp_path
        })
    }
    // 生成参数与属性数组 attrs
    let attrs = []
    if(manyCheckList.value.length>0){
        manyCheckList.value.forEach((val,index)=>{
            if(val instanceof Array){
                val.forEach(val1=>[
                    attrs.push({
                        attr_id:manyParams.value[index].attr_id,
                        attr_value:val1
                    })
                ])
            }
        })
    }
    // 遍历需要被选中的静态属性数组
    // 不为空的才需要遍历
    if(onlyRadioList.value.length > 0){
        onlyRadioList.value.forEach((val,index) =>{
            // 有些索引号下没有值
            if(!val) return
            attrs.push({
                attr_id:onlyParmas.value[index].attr_id,
                attr_value:val
            })
        })
    }  
    const {data:res} = await axios.post('goods',{
        goods_name:goodsForm.goods_name,
        // goods_cat需要转换为逗号连接的字符串
        goods_cat: goodsForm.goods_cat.join(","),
        goods_price: goodsForm.goods_price,
        goods_number: goodsForm.goods_number,
        goods_weight: goodsForm.goods_weight,
        goods_inroduce: goods_inroduce.value,
        pics:pics,
        attrs:attrs

    })
    console.log(res);
    if(res.meta.status !== 201)
        return ElMessage.error(res.meta.msg)
    else
     router.push('/homes/goods')
}
</script>
<style>
.el-alert {
    display: flex;
    justify-content: center;
}

.el-steps {
    margin: 30px 0;
}

.el-input {
    width: 500px;
}

.editor {
    margin: 10px auto;
}
</style>